/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License,Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import hilog from '@ohos.hilog';
import Ability from '@ohos.application.Ability'
import accessControl from "@ohos.abilityAccessCtrl";
import bundle from '@ohos.bundle';
import Window from '@ohos.window'

const BUNDLE_NAME = "com.example.distrubutedmusicplayer"
const PERMISSION_REJECT = -1

export default class MainAbility extends Ability {
    onNewWant(want, launchParams) {
        globalThis.newWant = want
        hilog.info(0x0000, 'MyOpenHarmonyPlayer', '%{public}s', 'onNewWant launchParam:' + JSON.stringify(launchParams) ?? '');
    }

    onCreate(want, launchParam) {
        globalThis.newWant = want
        hilog.isLoggable(0x0000, 'MyOpenHarmonyPlayer', hilog.LogLevel.INFO);
        hilog.info(0x0000, 'MyOpenHarmonyPlayer', '%{public}s', 'Ability onCreate');
        hilog.info(0x0000, 'MyOpenHarmonyPlayer', '%{public}s', 'want param:' + JSON.stringify(want) ?? '');
        hilog.info(0x0000, 'MyOpenHarmonyPlayer', '%{public}s', 'launchParam:' + JSON.stringify(launchParam) ?? '');
    }

    onDestroy() {
        hilog.isLoggable(0x0000, 'MyOpenHarmonyPlayer', hilog.LogLevel.INFO);
        hilog.info(0x0000, 'MyOpenHarmonyPlayer', '%{public}s', 'Ability onDestroy');
    }

    onWindowStageCreate(windowStage: Window.WindowStage) {
        // Main window is created, set main page for this ability
        hilog.isLoggable(0x0000, 'MyOpenHarmonyPlayer', hilog.LogLevel.INFO);
        hilog.info(0x0000, 'MyOpenHarmonyPlayer', '%{public}s', 'Ability onWindowStageCreate');

        windowStage.loadContent('pages/main', (err, data) => {
            if (err.code) {
                hilog.isLoggable(0x0000, 'MyOpenHarmonyPlayer', hilog.LogLevel.ERROR);
                hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
                return;
            }
            hilog.isLoggable(0x0000, 'MyOpenHarmonyPlayer', hilog.LogLevel.INFO);
            hilog.info(0x0000, 'MyOpenHarmonyPlayer', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
        });
    }

    onWindowStageDestroy() {
        // Main window is destroyed, release UI related resources
        hilog.isLoggable(0x0000, 'MyOpenHarmonyPlayer', hilog.LogLevel.INFO);
        hilog.info(0x0000, 'MyOpenHarmonyPlayer', '%{public}s', 'Ability onWindowStageDestroy');
    }

    onForeground() {
        // Ability has brought to foreground
        hilog.isLoggable(0x0000, 'MyOpenHarmonyPlayer', hilog.LogLevel.INFO);
        hilog.info(0x0000, 'MyOpenHarmonyPlayer', '%{public}s', 'Ability onForeground');
    }

    onBackground() {
        // Ability has back to background
        hilog.isLoggable(0x0000, 'MyOpenHarmonyPlayer', hilog.LogLevel.INFO);
        hilog.info(0x0000, 'MyOpenHarmonyPlayer', '%{public}s', 'Ability onBackground');
    }

    requestPermissions = async () => {
        let permissions: Array<string> = [
            "ohos.permission.DISTRIBUTED_DATASYNC"
        ];
        let needGrantPermission = false
        let accessManger = accessControl.createAtManager()
        hilog.info(0x0000,'MyOpenHarmonyPlayer',"app permission get bundle info")
        let bundleInfo = await bundle.getApplicationInfo(BUNDLE_NAME, 0, 100)
        hilog.info(0x0000,'MyOpenHarmonyPlayer',`app permission query permission ${bundleInfo.accessTokenId.toString()}`)
        for (const permission of permissions) {
            hilog.info(0x0000,'MyOpenHarmonyPlayer',`app permission query grant status ${permission}`)
            try {
                let grantStatus = await accessManger.verifyAccessToken(bundleInfo.accessTokenId, permission)
                if (grantStatus === PERMISSION_REJECT) {
                    needGrantPermission = true
                    break;
                }
            } catch (err) {
                hilog.error(0x0000,'MyOpenHarmonyPlayer',`app permission query grant status error ${permission} ${JSON.stringify(err)}`)
                needGrantPermission = true
                break;
            }
        }
        if (needGrantPermission) {
            hilog.info(0x0000,'MyOpenHarmonyPlayer',"app permission needGrantPermission")
            try {
                await this.context.requestPermissionsFromUser(permissions)
            } catch (err) {
                hilog.error(0x0000,'MyOpenHarmonyPlayer',`app permission ${JSON.stringify(err)}`)
            }
        } else {
            hilog.info(0x0000,'MyOpenHarmonyPlayer',"app permission already granted")
        }
    }
}
